To use it as a model for QTableView with PostgreSQL 9.1 on PySide2, I subclass QSqlTableModel and rewrite the function insertRowIntoTable (assuming the primary key of serial type is the first field of the record) :
def insertRowIntoTable(self, values):
if QSqlTableModel.insertRowIntoTable(self, values):
# returns the value of the primary key "autovalue" (serial) only when the record is added in database
rs = QSqlQuery()
rs.exec_("SELECT CURRVAL (pg_get_serial_sequence('public." + self.tableName() + "','"+ self.primaryKey().field(0).name() +"'))")
if rs.next():
ID = rs.value(0)
# without this line the row displayed in the QTableView immediately after insertion cannot be updated
self.setData (self.index(self.rowCount()-1,0), ID)
# without this line the created row appears blank in the QTableView
values.remove(0)
return True
return False